﻿using System;
using System.Web.UI;
using Twipler.App;
using Twipler.Data.Access;
using Twipler.WebApp;

namespace TwiplerWeb.Settings.User
{
	[RequireUser()]
	[QueryStringHash]
	public partial class Account : Page
	{
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Current.SessionTrack.OAuthToken == null)
            {
                btnCreatePassword.Enabled = false;
                litError.Text = "<div class=errormessage>This is not available with basic authentication.</div>";
            }

            if (!IsPostBack)
                chkStayLoggedIn.Checked = Response.Cookies["AutoLoginId"] != null && string.IsNullOrEmpty(Response.Cookies["AutoLoginId"].Value);
        }

		protected void btnCreatePassword_Click(object sender, EventArgs e)
		{
			if (txtPassword.Text.Trim().Length < 5)
			{
				litError.Text = "<div class=errormessage>Password must be at least 6 characters long</div>";
				return;
			}

			Current.Visitor.OAuthToken = Current.SessionTrack.OAuthToken.Encrypt(txtPassword.Text.Trim());
			Factory.Visitor.SaveOrUpdate(Current.Visitor);

			litError.Text = "<div class=successmessage>You session has been password protected</div>";

            System.Web.HttpCookie cookie = new System.Web.HttpCookie("AutoLoginId", "");
            cookie.Expires = DateTime.Now.AddDays(10000);
            cookie.Path = "/";

            cookie.Value = chkStayLoggedIn.Checked 
                ? Current.Visitor.ScreenName + " " + txtPassword.Text.Trim()
                : string.Empty;

            Response.Cookies.Add(cookie);
		}
	}
}
